#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
健康检查脚本
用于检查应用和数据库的运行状态
"""

import requests
import pymysql
import json
import sys
import os
from datetime import datetime

def load_config():
    """加载配置文件"""
    try:
        # 从scripts目录访问根目录的config.json
        config_path = os.path.join(os.path.dirname(os.path.dirname(__file__)), 'config.json')
        with open(config_path, 'r') as f:
            return json.load(f)
    except Exception as e:
        print(f"❌ 配置文件加载失败: {e}")
        return None

def check_web_service():
    """检查Web服务状态"""
    print("🌐 检查Web服务...")
    
    try:
        config = load_config()
        if not config:
            return False
        
        server_config = config.get('server', {})
        host = server_config.get('host', 'localhost')
        port = server_config.get('port', 5000)
        
        # 如果host是0.0.0.0，改为localhost进行测试
        if host == '0.0.0.0':
            host = 'localhost'
        
        url = f"http://{host}:{port}/login"
        
        response = requests.get(url, timeout=10)
        
        if response.status_code == 200:
            print(f"  ✅ Web服务正常 ({url})")
            return True
        else:
            print(f"  ❌ Web服务异常 (状态码: {response.status_code})")
            return False
            
    except requests.exceptions.ConnectionError:
        print(f"  ❌ Web服务连接失败 - 服务可能未启动")
        return False
    except Exception as e:
        print(f"  ❌ Web服务检查失败: {e}")
        return False

def check_mysql_connection():
    """检查MySQL数据库连接"""
    print("🗄️  检查MySQL数据库...")
    
    try:
        config = load_config()
        if not config:
            return False
        
        mysql_config = config.get('mysql', {})
        
        connection = pymysql.connect(
            host=mysql_config.get('host', 'localhost'),
            port=mysql_config.get('port', 3306),
            user=mysql_config.get('username', 'root'),
            password=mysql_config.get('password', ''),
            database=mysql_config.get('database', 'mongod_sys'),
            charset='utf8mb4',
            connect_timeout=10
        )
        
        with connection.cursor() as cursor:
            # 检查用户表
            cursor.execute("SELECT COUNT(*) FROM users")
            user_count = cursor.fetchone()[0]
            
            # 检查连接表
            table_name = mysql_config.get('table', 'mongodb_connections')
            cursor.execute(f"SELECT COUNT(*) FROM {table_name}")
            connection_count = cursor.fetchone()[0]
            
            print(f"  ✅ MySQL连接正常")
            print(f"     用户数量: {user_count}")
            print(f"     连接配置数量: {connection_count}")
        
        connection.close()
        return True
        
    except Exception as e:
        print(f"  ❌ MySQL连接失败: {e}")
        return False

def check_login_api():
    """检查登录API"""
    print("🔐 检查登录API...")
    
    try:
        config = load_config()
        if not config:
            return False
        
        server_config = config.get('server', {})
        host = server_config.get('host', 'localhost')
        port = server_config.get('port', 5000)
        
        if host == '0.0.0.0':
            host = 'localhost'
        
        url = f"http://{host}:{port}/api/login"
        
        # 测试错误的登录信息
        response = requests.post(
            url,
            json={"username": "test", "password": "wrong"},
            headers={"Content-Type": "application/json"},
            timeout=10
        )
        
        if response.status_code == 401:
            print(f"  ✅ 登录API正常 (正确拒绝无效凭据)")
            return True
        else:
            print(f"  ❌ 登录API异常 (状态码: {response.status_code})")
            return False
            
    except Exception as e:
        print(f"  ❌ 登录API检查失败: {e}")
        return False

def main():
    """主函数"""
    print("🏥 MongoDB用户管理工具 - 健康检查")
    print(f"⏰ 检查时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
    print("=" * 50)
    
    checks = [
        ("Web服务", check_web_service),
        ("MySQL数据库", check_mysql_connection),
        ("登录API", check_login_api),
    ]
    
    results = []
    
    for name, check_func in checks:
        try:
            result = check_func()
            results.append((name, result))
        except Exception as e:
            print(f"❌ {name}检查出错: {e}")
            results.append((name, False))
        print()
    
    # 汇总结果
    print("=" * 50)
    print("📊 检查结果汇总:")
    
    all_passed = True
    for name, result in results:
        status = "✅ 正常" if result else "❌ 异常"
        print(f"  {name}: {status}")
        if not result:
            all_passed = False
    
    print("=" * 50)
    
    if all_passed:
        print("🎉 所有检查通过，系统运行正常！")
        sys.exit(0)
    else:
        print("⚠️  发现问题，请检查上述异常项目")
        sys.exit(1)

if __name__ == "__main__":
    main()